- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathEditDistance.java
73 lines (55 loc) Β· 1.75 KB
/
EditDistance.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
packagesection19_DynamicProgramming;
publicclassEditDistance {
publicstaticvoidmain(String[] args) {
Strings1 = "agbg";
Strings2 = "acgb";
System.out.println(editDistance(s1, s2)); // 2
System.out.println(editDistanceIterative(s1, s2)); // 2
}
// minimum changes required to make s2 equal to s1
// O(2^nm) Time, where n is length of s1, m is length of s2
publicstaticinteditDistance(Strings1, Strings2) {
if (s1.length() == 0)
returns2.length();
if (s2.length() == 0)
returns1.length();
Stringros1 = s1.substring(1);
Stringros2 = s2.substring(1);
intresult = 0;
if (s1.charAt(0) == s2.charAt(0)) {
result = editDistance(ros1, ros2);
} else {
intremoveFactor = 1 + editDistance(ros1, ros2);
intaddFactor = 1 + editDistance(ros1, s2);
intreplaceFactor = 1 + editDistance(s1, ros2);
result = Math.min(removeFactor, Math.min(addFactor, replaceFactor));
}
returnresult;
}
// DP approach
// O(nm) Time, where n is length of s1, m is length of s2
publicstaticinteditDistanceIterative(Strings1, Strings2) {
int[][] storage = newint[s1.length() + 1][s2.length() + 1];
// seed value
storage[s1.length()][s2.length()] = 0;
for (introw = s1.length(); row >= 0; row--) {
for (intcol = s2.length(); col >= 0; col--) {
if (row == s1.length()) {
storage[row][col] = s2.length() - col;
continue;
}
if (col == s2.length()) {
storage[row][col] = s1.length() - row;
continue;
}
if (s1.charAt(row) == s2.charAt(col)) {
storage[row][col] = storage[row + 1][col + 1];
} else {
storage[row][col] = 1 + Math.min(storage[row + 1][col + 1],
Math.min(storage[row + 1][col], storage[row][col + 1]));
}
}
}
returnstorage[0][0];
}
}